#!/bin/bash

# 修复xiaozhi用户和权限问题的脚本
set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "请使用sudo运行此脚本"
        exit 1
    fi
}

# 创建xiaozhi用户
create_user() {
    log_info "检查xiaozhi用户..."
    
    if id "xiaozhi" &>/dev/null; then
        log_success "xiaozhi用户已存在"
    else
        log_info "创建xiaozhi用户..."
        useradd -r -s /bin/bash -d /opt/xiaozhi-server -c "XiaoZhi ESP32 Server" xiaozhi
        log_success "xiaozhi用户创建成功"
    fi
    
    # 设置用户目录
    if [[ ! -d "/opt/xiaozhi-server" ]]; then
        log_info "创建/opt/xiaozhi-server目录..."
        mkdir -p /opt/xiaozhi-server
    fi
    
    # 设置目录权限
    log_info "设置目录权限..."
    chown -R xiaozhi:xiaozhi /opt/xiaozhi-server
    chmod 755 /opt/xiaozhi-server
    
    # 创建日志目录
    if [[ ! -d "/tmp/xiaozhi-logs" ]]; then
        log_info "创建日志目录..."
        mkdir -p /tmp/xiaozhi-logs
        chown -R xiaozhi:xiaozhi /tmp/xiaozhi-logs
    fi
}

# 创建启动脚本
create_start_script() {
    log_info "创建启动脚本..."
    
    cat > /opt/xiaozhi-server/start_server.sh << 'EOF'
#!/bin/bash

# 小智ESP32服务器启动脚本
cd /opt/xiaozhi-server

# 激活conda环境
source /opt/miniconda3/etc/profile.d/conda.sh
conda activate xiaozhi-server

# 启动服务
exec python app.py
EOF

    chmod +x /opt/xiaozhi-server/start_server.sh
    chown xiaozhi:xiaozhi /opt/xiaozhi-server/start_server.sh
    log_success "启动脚本创建成功"
}

# 复制项目文件
copy_project_files() {
    log_info "复制项目文件..."
    
    # 获取当前脚本所在目录
    CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    
    if [[ -d "$CURRENT_DIR" ]]; then
        log_info "从 $CURRENT_DIR 复制文件到 /opt/xiaozhi-server"
        
        # 复制项目文件
        cp -r "$CURRENT_DIR"/* /opt/xiaozhi-server/
        
        # 设置权限
        chown -R xiaozhi:xiaozhi /opt/xiaozhi-server
        
        log_success "项目文件复制完成"
    else
        log_error "当前目录不存在: $CURRENT_DIR"
        exit 1
    fi
}

# 重新加载systemd配置
reload_systemd() {
    log_info "重新加载systemd配置..."
    systemctl daemon-reload
    log_success "systemd配置已重新加载"
}

# 测试服务
test_service() {
    log_info "测试服务启动..."
    
    # 停止服务（如果正在运行）
    systemctl stop xiaozhi-server 2>/dev/null || true
    
    # 启动服务
    if systemctl start xiaozhi-server; then
        sleep 3
        if systemctl is-active --quiet xiaozhi-server; then
            log_success "服务启动成功！"
            return 0
        else
            log_error "服务启动失败"
            return 1
        fi
    else
        log_error "服务启动失败"
        return 1
    fi
}

# 显示状态
show_status() {
    log_info "服务状态："
    echo "========================================"
    systemctl status xiaozhi-server --no-pager -l
    echo "========================================"
    
    log_info "xiaozhi用户信息："
    id xiaozhi
    echo "========================================"
    
    log_info "目录权限："
    ls -la /opt/xiaozhi-server/
    echo "========================================"
}

# 主函数
main() {
    check_root
    
    log_info "开始修复xiaozhi用户和权限问题..."
    
    create_user
    copy_project_files
    create_start_script
    reload_systemd
    
    if test_service; then
        show_status
        log_success "修复完成！服务已成功启动"
        log_info "您可以使用以下命令查看日志："
        log_info "  sudo ./manage_service.sh logs service 100"
        log_info "  sudo ./manage_service.sh follow service"
    else
        log_error "修复失败，请检查日志："
        log_info "  sudo ./manage_service.sh logs service 100"
        exit 1
    fi
}

# 运行主函数
main "$@"